package com.guli.msmservice.controller;

import com.guli.commonutils.R;
import com.guli.msmservice.service.MsmService;
import com.guli.msmservice.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(tags = "短信服务")
@RestController
@RequestMapping("/edumsm/msm")
@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @ApiOperation(value = "发送短信,5分钟有效")
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable("phone") String phone) {
        //从redis中获取验证码，若存在则返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok();
        }
        //redis中不存在则发送
        //生产随机验证码
        code = RandomUtil.getFourBitRandom();
        //调用service中发送方法
        boolean isSend = msmService.send(code, phone);
        if (isSend) {
            //发送成功则设置到redis中，存活时间5min
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}